﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SmartSpace.Core
{
    public partial class CoreService :ICoreService
    {
        public bool SaveUserGroup(UserGroup group)
        {
            using (CoreContext context = _contextFactory.Get())
            {
                EntityRepository.Save(group, context.DbContext);

                return EntityRepository.Commit(context.DbContext);
            }
        }

        public bool DeleteUserGroup(UserGroup group)
        {
            using (CoreContext context = _contextFactory.Get())
            {
                if (!EntityRepository.Delete(group, context.DbContext))
                {
                    return false;
                }
                return EntityRepository.Commit(context.DbContext);
            }
        }

        public UserGroup GetUserGroup(Guid groupId)
        {
            using (CoreContext context = _contextFactory.Get())
            {
                return context.Set<UserGroup>()
                    .Include("Users")
                    .Where(p => p.Id == groupId)
                    .SingleOrDefault();
            }
        }

        public List<UserGroup> GetUserGroups()
        {
            using (CoreContext context = _contextFactory.Get())
            {
                return context.Set<UserGroup>()
                    .OrderBy(p => p.SortIndex)
                    .ToList();
            }
        }

        public PagedList<User> GetUserGroupContainUsers(Guid id, int start, int limit)
        {
            using (CoreContext context = _contextFactory.Get())
            {
                string sql = "select u.* from __user as u join __RelationUserToUserGroup as r on r.userid=u.id where r.usergroupid={0} order by u.account";
                int total = context.Database.SqlQuery<User>(sql, id).Count();
                List<User> users = context.Database.SqlQuery<User>(sql, id).Take(limit).Skip(start).ToList();

                PagedList<User> pagedUser = new PagedList<User>();
                pagedUser.AddRange(users);
                pagedUser.Start = start;
                pagedUser.Limit = limit;
                pagedUser.Total = total;

                return pagedUser;
            }
        }

        public bool AssignUserToUserGroup(Guid userId, Guid groupId)
        {
            using (CoreContext context = _contextFactory.Get())
            {
                User user = context.Set<User>().Where(p => p.Id == userId).SingleOrDefault();

                UserGroup group = context.Set<UserGroup>().Where(p => p.Id == groupId).SingleOrDefault();

                user.UserGroups.Add(group);

                EntityRepository.Save<User>(user, context.DbContext);

                return EntityRepository.Commit(context.DbContext);
            }
        }
    }
}
